from django.contrib.auth import get_user_model
from rest_framework import serializers

from answer.models import Answer
from answer.serializer import AnswerDetailSer
from comment.models import Comment
from questions.models import Question
from questions.serializer import QuestionDetailSer

User = get_user_model()


class CommentAnswerSer(serializers.ModelSerializer):
    # be referenced
    creator = serializers.ReadOnlyField(source='creator.id')
    answer_id = serializers.IntegerField()

    class Meta:
        model = Comment
        fields = (
            'id',
            'content',
            'created_time',

            # foreign key
            'creator',
            'answer_id',
        )

    def create(self, validated_data):
        answer_id = validated_data.pop('answer_id', None)

        if answer_id:
            try:
                answer = Answer.objects.get(id=answer_id)
                comment = Comment.objects.create(answer=answer, **validated_data)
                return comment
            except Answer.DoesNotExist:
                raise serializers.ValidationError('answer_id is invalid')
        raise serializers.ValidationError('answer_id is required')


class CommentQuestionSer(serializers.ModelSerializer):
    # be referenced
    creator = serializers.ReadOnlyField(source='creator.id')
    question_id = serializers.IntegerField(required=False)

    class Meta:
        model = Comment
        fields = (
            'id',
            'content',
            'created_time',

            # foreign key
            'creator',
            'question_id',
        )

    def create(self, validated_data):
        question_id = validated_data.pop('question_id', None)

        if question_id:
            try:
                question = Question.objects.get(id=question_id)
                comment = Comment.objects.create(question=question, **validated_data)
                return comment
            except Question.DoesNotExist:
                raise serializers.ValidationError('question_id is invalid')
        raise serializers.ValidationError('question_id is required')


class CommentUpdateSer(serializers.ModelSerializer):
    class Meta:
        model = Comment
        fields = (
            'id',
            'content',
            'created_time',

        )


class CommentDetailSer(serializers.ModelSerializer):
    from account.serializer import UserForeignKeySer
    creator = UserForeignKeySer(read_only=True)
    question = QuestionDetailSer(read_only=True)
    answer = AnswerDetailSer(read_only=True)

    class Meta:
        model = Comment
        fields = (
            'id',
            'content',
            'created_time',

            # foreign key
            'creator',
            'question',
            'answer',
        )


class CommentForeignKeySer(serializers.ModelSerializer):
    class Meta:
        model = Comment
        fields = (
            'id',
            'content',
            'created_time',

        )
